<?php

namespace App\Imports;

use App\Models\VideoLibrary;
use App\Models\VideoLibraryCategory;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Concerns\ToCollection;

class VideoImport implements ToCollection
{
    protected int $categoryId;

    public function __construct($categoryId=0)
    {
            $this->categoryId = $categoryId;
    }

    /**
     * @param Collection $collection
     * @throws \Throwable
     */
    public function collection(Collection $collection)
    {
        //如果需要去除表头
        unset($collection[0]);
        //$rows 是数组格式
        $this->createData($collection);
    }

    /**
     * @param $collection
     * @return void
     * @throws \Throwable
     */
    public function createData($collection)
    {
        DB::transaction(function () use ($collection) {
            $successCount = 0;
            $successIds = [];

            foreach ($collection as $k=>$item) {
                $fileFormat = !empty($item[4]) ? $item[4] : 'mp4';

                $v = VideoLibrary::create([
                    'category_id' => $this->categoryId,
                    'name' => $item[0],
                    'total_size' => $item[2],
                    'total_second' => $item[3],
                    'video_format' => $fileFormat,
                    'video_url' => $item[1],
                ]);

                if ($v) {
                    $successCount += 1;
                    $successIds[] = $v->id;
                }
            }

            // 更新分类的视频数量
            if ($this->categoryId)
                VideoLibraryCategory::where('id', $this->categoryId)->increment('videoCount', $successCount);

            \Log::info('视频EXCEL导入('.$successCount.'个)', $successIds);
        });
    }
}
